package org.kardigen.lg.admin.client.training;

import org.kardigen.lg.admin.client.training.event.ChapterSelectionEvent;
import org.kardigen.lg.service.client.proxy.TrainingProxy;
import org.kardigen.lg.service.client.requestfactory.TrainingRequestContext;
import org.kardigen.lg.service.client.requestfactory.TrainingRequestFactory;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.requestfactory.shared.Receiver;
import com.google.gwt.user.client.Window;

public class TrainingEditorViewPresenter implements TrainingEditorViewDisplay.Presenter {

	private final TrainingEditorViewDisplay display;
	private EventBus eventBus;
	private TrainingRequestFactory requestFactory;
	private TrainingRequestContext requestContext;
	private TrainingProxy model;
	private TrainingProxy originalProxy;

	public TrainingEditorViewPresenter(TrainingEditorViewDisplay display) {
		this.display = display;
		display.setPresenter(this);

	}

	public void onSave() {
		String value = display.getTrainingName().getValue();
		if (value != null && !value.trim().isEmpty()) {
			model.setTrainingName(value);
			requestContext.saveTraining(model)
			.with("chapters","chapters.words")
			.fire(new Receiver<TrainingProxy>() {

				@Override
				public void onSuccess(TrainingProxy response) {
					if (response == null) {
						Window.alert("Cannot save training!");
					} else {
						Window.alert("Training saved!");
						requestContext = requestFactory.createTrainingRequestContext();
						model = requestContext.edit(response);
					}
				}
			});
		}
	}

	public void start(TrainingProxy trainingProxy, EventBus eventBus) {
		this.originalProxy = trainingProxy;
		this.eventBus = eventBus;
		initializeRequestFactory();
		requestContext = requestFactory.createTrainingRequestContext();

		display.getTrainingName().setValue("");

		if (trainingProxy == null) {
			model = requestContext.create(TrainingProxy.class);
			display.getLabel().setText("Creating new training");
		} else {
			model = requestContext.edit(trainingProxy);
			display.getLabel().setText("Editing training: " + trainingProxy.getTrainingName());
		}
	}

	private void initializeRequestFactory() {
		if (requestFactory == null) {
			requestFactory = GWT.create(TrainingRequestFactory.class);
			requestFactory.initialize(eventBus);
		}
	}

	public void onAddChapter() {
		eventBus.fireEvent(new ChapterSelectionEvent(originalProxy, null));
	}

}
